<template>
  <div class="addCaliber">
    <el-dialog
      title="新增指标口径"
      :visible.sync="addCaliberVisible"
      v-dialogDrag
      width="50%"
      @close="closeAddCaliberDialog"
      :close-on-click-modal="false"
    >
      <el-form
        label-width="80px"
        label="right"
        :model="addForm"
        :rules="rules"
        ref="addForm"
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effectDt">
              <el-date-picker
                v-model="addForm.effectDt"
                type="date"
                placeholder="选择日期"
                :picker-options="startTime"
                class="caliberDefFilter"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效日期">
              <el-date-picker
                v-model="addForm.invalidDt"
                type="date"
                placeholder="选择日期"
                :picker-options="endTime"
                class="caliberDefFilter"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="口径编号" prop="caliberNo">
              <el-input
                class="caliberDefFilter"
                v-model.trim="addForm.caliberNo"
                placeholder="请输入"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="口径属性" prop="caliberDefAttr">
              <el-select
                v-model="addForm.caliberDefAttr"
                placeholder="请选择"
                @change="selectDefAttr($event)"
                class="caliberDefFilter"
              >
                <el-option
                  v-for="item in caliberDefAttrOptions"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="口径名称" prop="caliberName">
              <el-input
                placeholder="请输入"
                v-model.trim="addForm.caliberName"
                maxlength="40"
                class="caliberDefFilter"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="口径描述">
              <el-input
                placeholder="请输入"
                v-model="addForm.caliberDesc"
                maxlength="40"
                class="caliberDefFilter"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="口径范围" required>
              <div v-show="treeShow" @click="treeOrGrid">
                <el-input
                  placeholder="请选择"
                  v-model="addForm.caliberDefFilter"
                  disabled
                  class="caliberDefFilter"
                  v-if="selectDefAttrShow"
                >
                  <!-- 树形icon -->
                  <i slot="suffix" class="el-icon-date"></i>
                </el-input>
              </div>
              <!-- 0305 -->
              <div v-show="gridShow" v-popover:popover>
                <el-input
                  placeholder="请选择"
                  v-model="addForm.caliberDefFilter"
                  disabled
                  class="caliberDefFilter"
                  v-if="selectDefAttrShow"
                >
                  <i slot="suffix" class="el-icon-s-grid"></i>
                </el-input>
              </div>

              <!-- 0305-->
              <!--选择框 -->
              <el-select
                v-if="!selectDefAttrShow"
                v-model="addForm.caliberDefFilters"
              >
                <el-option
                  v-for="item in caliberDefAttrfw"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
              <el-popover
                ref="popover"
                @show="selectDefAttrGrid"
                placement="top"
                v-model="caliberGridDataShow"
                trigger="click"
              >
                <div>
                  <el-button @click="caliberSelectionChanges">确定</el-button>
                  <el-table
                    highlight-current-row
                    @selection-change="caliberSelectionChange"
                    :data="caliberTableData"
                    height="200"
                  >
                    <el-table-column
                      type="selection"
                      width="55"
                    ></el-table-column>
                    <el-table-column
                      :prop="this.tableKey"
                      label="编号"
                    ></el-table-column>
                    <el-table-column
                      :prop="this.tableValue"
                      label="名称"
                    ></el-table-column>
                  </el-table>
                  <pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    @refresh="selectPageDefAttrGrid"
                    :page-size="size"
                    :total="total"
                  ></pagination>
                </div>
              </el-popover>

              <!-- /////////////////////////////// -->

              <!-- 表格 -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input
                placeholder="请输入"
                v-model="addForm.memo"
                maxlength="40"
                class="caliberDefFilter"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="addCaliberM">确定</el-button>
        <el-button size="small" @click="cancelCaliberM">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 树形结构图 -->
    <el-dialog
      :title="this.treeTitle"
      :visible.sync="treeNode"
      width="30%"
      :close-on-click-modal="false"
    >
      <div style="height: 300px; overflow-y: auto">
         <vp-tree
          v-if="treeKey"
          :vp-header="{show:true,text:'已构建关系树',search:true,name:this.treeValue}"
          :node-key="treeKey"
          :data="caliberTreeData"
          show-checkbox
          :default-expand-all="treeExpand"
          ref="tree"
          highlight-current
          :filter-node-method="filterNode"
          :props="defaultProps"
        ></vp-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="increaseTreeConfirms">确定</el-button>
        <el-button size="small" @click="cancelTree">取消</el-button>
      </span>
    </el-dialog>
    <!-- 表格 -->
    <!-- 下拉框 -->
  </div>
</template>
<script>
import { listToTree } from "@/lib/util"; // list转tree
import vpTree from "@/components/vpTree";
import { DatasCenter } from "@/api/index";
export default {
  props: [
    "addCaliberVisible",
    "addCaliberM",
    "cancelCaliberM",
    "closeAddCaliberDialog",
  ],
  name: "addCaliber",
  data() {
    return {
      selectData: [],
      selectTreeKey: [],
      selectedTreeDatas: [],
      startTime: {
        disabledDate: (time) => {
          if (this.addForm.effectDt) {
            return time.getTime() > new Date(this.addForm.invalidDt).getTime();
          }
        },
      },
      // 结束时间大于开始时间
      endTime: {
        disabledDate: (time) => {
          if (this.addForm.effectDt) {
            return time.getTime() < new Date(this.addForm.effectDt).getTime();
          }
        },
      },
      // 第几页
      page: 1,
      // 页面展示个数
      size: 15,
      // 总数
      total: 0,
      treeTitle: "", // 树形图标题
      tableArr: [],
      tableKey: "", // 表格数据key值
      tableValue: "", //
      treeArr: [], //
      treeKey: "", // 树形id值
      treeValue: "", // 树形value值
      treeProKey: "", // 树形父级id值
      caliberTableDataSearch: "", // 表格搜索
      caliberTableData: [], // 表格数据
      caliberGridDataShow: false, // 表格是否显示
      selectedTreeData: [], //选中的树形结构ID
      selectedTreeName: [], // 选中的树形数据名称
      defaultProps: {
        children: "children",
        label: this.treeValue,
      },
      treeExpand: false, // 是否展开
      filterText: "", // 树形搜索
      treeNode: false, //树形弹框显示隐藏
      caliberTreeData: [], // 树形图数据
      gridShow: false, // 表格icon
      addcaliberDefAttrfw: "", // 属性范围下拉框数据绑定
      caliberDefAttrfw: [], // 属性范围下拉框
      treeShow: false, // 树行icon
      selectDefAttrShow: true, // 输入框的显示隐藏
      defAttrId: "", // 选择的口径属性id
      selectDefAttrId: "", //树形结构图标题
      caliberDefAttrOptions: [], //口径属性
      flexibleModelAttrs: [], // 口径属性显示方式集合
      addForm: {
        effectDt: "",
        invalidDt: "",
        caliberNo: "",
        caliberName: "",
        caliberDesc: "",
        caliberDefAttr: "",
        caliberDefFilter: "",
        memo: "",
        uuid: "",
        caliberDefFilterId: "",
        caliberDefFilters: "", // 下拉选择框
      },
      // 规则
      rules: {
        effectDt: [
          {
            required: true,
            trigger: "change",
            message: "请填写生效日期",
          },
        ],
        caliberNo: [
          {
            required: true,
            trigger: "blur",
            validator: this.validateCaliberNo,
          },
        ],
        caliberName: [
          {
            required: true,
            trigger: "blur",
            message: "请填写口径名称",
          },
        ],
        caliberDefFilter: [
          {
            required: true,
            trigger: "blur",
            message: "请选择口径范围",
          },
        ],
        caliberDefAttr: [
          {
            required: true,
            trigger: "change",
            message: "请选择口径属性",
          },
        ],
      },
    };
  },
  watch: {
  },
  mounted() {},
  methods: {
    isCaliberNoAvailable(value) {
      let myreg = /^[a-zA-Z][a-zA-Z0-9_]{0,7}$/;
      if (!myreg.test(value)) {
        return false;
      } else {
        return true;
      }
    },
    // 字段校验口径编号
    validateCaliberNo(rule, value, callback) {
      if (value === "") {
        callback(new Error("请填写口径编号"));
      } else if (!this.isCaliberNoAvailable(value)) {
        callback(new Error("输入1-8位字母数字下划线,字母开头"));
      } else {
        callback();
      }
    },
    // 口径名称
    validateCaliberName(rule, value, callback) {
      console.log(value, "value");
      if (value === "" || value == "undefined") {
        callback(new Error("请填写口径名称"));
      } else if (value.length > 40) {
        callback(new Error("口径名称不超过40位字符"));
      } else {
        callback();
      }
    },
    // 点击输入框
    treeOrGrid() {
      if (this.treeShow == true) {
        this.selectDefAttrTree();
      }
    },
    // 获取口径属性
    getCaliberDefAttrOptions() {
      DatasCenter.findCaliberAttrIndexBase().then((res) => {
        this.caliberDefAttrOptions = res.data;
      });
    },

    getFlexibleModelAttr() {
      DatasCenter.findFlexibleModelIndexBase().then((res) => {
        this.flexibleModelAttrs = res.data;
      });
    },
    // 选择口径属性
    selectDefAttr(id) {
      this.selectTreeKey = [];
      // 让所有的icon消失
      this.selectDefAttrShow = true;
      this.treeShow = false;
      this.gridShow = false;
      this.caliberGridDataShow = false;
      (this.addForm.caliberDefFilter = ""),
        (this.addForm.caliberDefFilterId = ""),
        // 口径属性id
        (this.defAttrId = id);

      // 树形弹框标题
      this.treeTitle = this.flexibleModelAttrs.find(
        (item) => item.fieldEn == id
      ).fieldName;
      // 下拉框
      if (
        this.flexibleModelAttrs.find((item) => item.fieldEn == id).fieldType ==
        "dict"
      ) {
        // 输入框树形icon都为隐藏
        this.selectDefAttrShow = false;
        this.treeShow = false;
        let urlParams = {
          dictId: id,
        };
        DatasCenter.queryDictIndexBase(urlParams).then((res) => {
          this.caliberDefAttrfw = res.data;
        });
      }
      // 树形菜单
      if (
        this.flexibleModelAttrs.find((item) => item.fieldEn == id).fieldType ==
        "tree"
      ) {
        (this.treeShow = true),
          (this.gridShow = false),
          (this.selectDefAttrShow = true);
      }
      // 表格
      if (
        this.flexibleModelAttrs.find((item) => item.fieldEn == id).fieldType ==
        "grid"
      ) {
        (this.treeShow = false),
          (this.gridShow = true),
          (this.selectDefAttrShow = true);
      }
    },
    // 点击表格icon
    selectDefAttrGrid() {
      (this.page = 1), (this.size = 15), (this.caliberTableData = []);
      this.tableArr = [];
      this.caliberGridDataShow = true;
      let id = this.defAttrId;
      let params = {
        page: Number(this.page),
        size: Number(this.size),
        tableName: this.flexibleModelAttrs.find((item) => item.fieldEn == id)
          .tableName,
        tableField: this.flexibleModelAttrs.find((item) => item.fieldEn == id)
          .tableField,
        tableFieldNameFiled: this.flexibleModelAttrs.find(
          (item) => item.fieldEn == id
        ).tableFieldNameFiled,
        isAssess: "",
      };
      DatasCenter.findGridIndexBase(params).then((res) => {
        this.caliberTableData = res.data;
        this.total = res.count;
        for (let key in this.caliberTableData[0]) {
          this.tableArr.push(key);
        }
        this.tableKey = this.tableArr[0];
        this.tableValue = this.tableArr[1];
      });
    },
    // 点击分页器的选择
    // 点击表格icon
    selectPageDefAttrGrid() {
      this.tableArr = [];
      let id = this.defAttrId;
      let params = {
        page: Number(this.page),
        size: Number(this.size),
        tableName: this.flexibleModelAttrs.find((item) => item.fieldEn == id)
          .tableName,
        tableField: this.flexibleModelAttrs.find((item) => item.fieldEn == id)
          .tableField,
        tableFieldNameFiled: this.flexibleModelAttrs.find(
          (item) => item.fieldEn == id
        ).tableFieldNameFiled,
        isAssess: "",
      };
      DatasCenter.findGridIndexBase(params).then((res) => {
        this.caliberTableData = res.data;
        this.total = res.count;
        for (let key in this.caliberTableData[0]) {
          this.tableArr.push(key);
        }
        this.tableKey = this.tableArr[0];
        this.tableValue = this.tableArr[1];
      });
    },
    // 选择表格中的一条数据
    caliberSelectionChange(val) {
      this.selectData = val;
    },
    caliberSelectionChanges() {
      let val = this.selectData;
      if (val) {
        var caliberNos = "";
        var caliberNames = "";
        if (val.length == 1) {
          caliberNos += val[0][this.tableKey];
          caliberNames += val[0][this.tableValue];
        } else {
          for (let i in val) {
            caliberNos += val[i][this.tableKey] + ",";
            caliberNames += val[i][this.tableValue] + ",";
          }
        }
        if (caliberNos[caliberNos.length - 1] == ",") {
          caliberNos = caliberNos.substring(0, caliberNos.length - 1);
        } else {
          caliberNos = caliberNos;
        }
        if (caliberNames[caliberNames.length - 1] == ",") {
          caliberNames = caliberNames.substring(0, caliberNames.length - 1);
        } else {
          caliberNames = caliberNames;
        }
        // 表格value赋值到input框
        this.$set(this.addForm, "caliberDefFilter", caliberNames);
        this.addForm.caliberDefFilterId = caliberNos;
        this.caliberGridDataShow = false;
      }
    },
    // 表格页码修改
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.selectPageDefAttrGrid();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.selectPageDefAttrGrid();
    },
    // 尺寸修改
    sizeChange(size) {
      this.size = size;
      this.selectPageDefAttrGrid();
    },
    // 页码修改
    currentChange(page) {
      this.page = page;
      this.selectPageDefAttrGrid();
    },
    // 刷新
    handlePaginationRefresh(boolean) {
      boolean && this.selectPageDefAttrGrid();
    },
    // 点击树形icon
    selectDefAttrTree() {
      (this.filterText = ""), (this.caliberTreeData = []);
      this.selectedTreeData = []; //选中的树形结构ID
      (this.treeKey = ""),
        (this.treeValue = ""),
        (this.treeProKey = ""),
        (this.selectedTreeName = []), // 选中的树形数据名称
        (this.treeNode = !this.treeNode);
      let id = this.defAttrId;
      // 获取树形数据
      let params = {
        fieldEn: this.flexibleModelAttrs.find((item) => item.fieldEn == id)
          .fieldEn,
        proFilter: "",
        treeId: "",
        tableName: this.flexibleModelAttrs.find((item) => item.fieldEn == id)
          .tableName,
        tableField: this.flexibleModelAttrs.find((item) => item.fieldEn == id)
          .tableField,
        tableFieldNameFiled: this.flexibleModelAttrs.find(
          (item) => item.fieldEn == id
        ).tableFieldNameFiled,
        tableFieldSuperior: this.flexibleModelAttrs.find(
          (item) => item.fieldEn == id
        ).tableFieldSuperior,
      };
      DatasCenter.findTreeIndexBase(params).then((res) => {
        this.treeArr = [];
        this.caliberTreeData = res.data;
        for (let key in this.caliberTreeData[0]) {
          this.treeArr.push(key);
        }
        this.treeKey = this.treeArr[1];
        this.treeValue = this.treeArr[2];
        this.treeProKey = this.treeArr[0];
        this.defaultProps.label = this.treeValue;

        // 找子节点
        this.caliberTreeData = listToTree(this.treeArr[1], this.treeProKey = this.treeArr[0], res.data);
        let that = this;
        this.$nextTick(() => {
          that.$refs.tree.$refs.vptree.setCheckedNodes(this.selectedTreeDatas);
          that.$refs.tree.$refs.vptree.setCheckedKeys(this.selectTreeKey);
        });
      });
    },
    // 搜索树形结构
    filterNode(value, data) {
      if (!value) return true;
      return data[this.treeValue].indexOf(value) !== -1;
    },
    // 树形弹框确定
    increaseTreeConfirms() {
      let selectedTreeDatas = [];
      this.selectedTreeData = this.$refs.tree.$refs.vptree.getCheckedNodes();
      for (let v of this.selectedTreeData) {
          if (!v.hasOwnProperty('children')) {
          selectedTreeDatas.push(v);
        }
      }
      this.selectedTreeData = selectedTreeDatas;
      let res = this.selectedTreeData;
      let arrName = [];
      let arrId = [];
      res.forEach((item) => {
        arrName.push(item[this.treeValue]);
        arrId.push(item[this.treeKey]);
      });
      (this.selectedTreeData = arrId), (this.selectedTreeName = arrName);

      if (!this.selectedTreeData.length > 0) {
        this.$message({
          message: "请选择数据",
          type: "warning",
        });
        return;
      }
      this.addForm.caliberDefFilter = this.selectedTreeName.toString();
      this.selectTreeKey = this.selectedTreeData;
      this.addForm.caliberDefFilterId = this.selectedTreeData;
      console.log(this.addForm.caliberDefFilterId, "999");
      this.treeNode = false;
    },
    cancelTree() {
      this.treeNode = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.caliberDefFilter {
  width: 80%;
}
</style>
